<script setup lang="ts">
  import { ref, watch, onMounted } from 'vue';
  import { useBooleanStore } from '@/store';
  import { Notification } from '@arco-design/web-vue';
  import { getMenu, saveRolePer } from '@/api/platform-management';

  const showDrawer = ref<boolean>(false);
  const booleanStore = useBooleanStore();

  const checkedKeys = ref<any[]>([]);
  // 监听弹框
  watch(
    () => booleanStore.boolValue3,
    (newValue: boolean) => {
      if (booleanStore.num3 === 5) showDrawer.value = newValue;
    }
  );
  // 当权限目录修改时
  watch(
    () => booleanStore.permissions,
    () => {
      checkedKeys.value = [];
      checkedKeys.value.push(...booleanStore.permissions[0]);
    }
  );

  function afterVisibleChange(val: any) {
    if (!val) {
      booleanStore.toggleBool3(5);
    }
  }
  function handleCancel() {
    booleanStore.toggleBool3(5);
  }
  const treeData = ref<any[]>([]);
  // 获取菜单
  async function getMenuList() {
    const data: any[] = await getMenu();
    treeData.value = data;
  }

  // 点击树节点
  function onCheck(item: any[]) {
    checkedKeys.value = [...(item as any[])];
  }

  // 保存权限
  async function handleOk() {
    const saveRoleData = {
      menus: checkedKeys.value,
      role: booleanStore.role[0],
    };
    const data = await saveRolePer(saveRoleData);
    if (data.retCode === '200') {
      booleanStore.toggleBool3(5);
      Notification.success({
        title: '成功',
        content: '权限保存成功',
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: '网络异常，请稍后重试',
        closable: true,
      });
    }
  }
  onMounted(() => {
    getMenuList();
  });
</script>

<template>
  <a-drawer
    :width="450"
    :height="340"
    :visible="showDrawer"
    placement="right"
    @after-visible-change="afterVisibleChange"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title> 菜单权限 </template>
    <div>
      <a-tree
        :checked-keys="checkedKeys"
        checkable
        :check-strictly="true"
        :data="treeData"
        :field-names="{
          key: 'id',
          title: 'label',
          children: 'children',
        }"
        @check="onCheck"
      />
    </div>
  </a-drawer>
</template>

<style scoped>
  .add {
    background-color: #bacf65;
    color: #fff;
  }
  .clear {
    margin-left: 10px;
  }
</style>
